﻿package com.badibadi.activity;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.json.JSONException;

import com.amap.api.location.AMapLocation;
import com.badibadi.adapter.AddingRecordNewAdapter;
import com.badibadi.adapter.Popwindows_Adapter;
import com.badibadi.infos.ClueTypeModel;
import com.badibadi.infos.ListsModel;
import com.badibadi.infos.Results;
import com.badibadi.infos.nearByModel;
import com.badibadi.mytools.AMapLocationUtils;
import com.badibadi.mytools.AMapLocationUtils.getAMapLocation;
import com.badibadi.mytools.Constants;
import com.badibadi.mytools.Dialog;
import com.badibadi.mytools.InterestModel;
import com.badibadi.mytools.JSONUtils;
import com.badibadi.mytools.MyThreadTool;
import com.badibadi.mytools.Utils;
import com.badibadi.uniclubber.R;
import com.badibadi.uniclubber.R.layout;
import com.badibadi.uniclubber.R.menu;
import com.nostra13.universalimageloader.core.DisplayImageOptions;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.nostra13.universalimageloader.core.display.RoundedBitmapDisplayer;
import com.view.my_view.XGridView;
import com.view.my_view.XGridView.OnXGridViewListener;
import com.view.my_view.XListView;
import com.view.my_view.XListView.IXListViewListener;

import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.graphics.drawable.BitmapDrawable;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.View;
import android.view.ViewGroup;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.LinearLayout.LayoutParams;
import android.widget.ListView;
import android.widget.PopupWindow;
import android.widget.TextView;

//chose_interest
public class PeopleNearByActivity extends BaseActivity implements
		OnClickListener, IXListViewListener {
	private XListView1Adapter x1Adapter;
	private XListView xListView1;
	private ListView type_list;
	private PopupWindow popup = null;
	private Popwindows_Adapter_1 adapter_1;
	private ImageView popwindows_display, popwindows_display_1;
	/** 每次加入的数量 */
	private int addNumber = 20;
	private AddingRecordNewAdapter arnAdapter;
	private Button returnButton;
	private Button chose_interest;
	private String interest_type = "0";
	private int GridViewNumColumns = 4;
	private int Page;
	private String jingdu = null, weidu = null;
	private static String TAG = "PeopleNearByActivity";
	final private int PopWindowsW = 300;
	final private int PopWindowsH = 500;
	private List<InterestModel> Interestlist;
	private List<nearByModel> main_byModels, byModels;
	private ListsModel listsModel;

	String uid;// 自己
	private Handler handler = new Handler() {
		@Override
		public void handleMessage(Message msg) {
			switch (msg.what) {
			case 1:
				Utils.ExitPrgress(PeopleNearByActivity.this);
				Utils.showMessage(PeopleNearByActivity.this, getResources()
						.getString(R.string.l_net_error));
				onLoad();
				break;
			case 2:
				Utils.ExitPrgress(PeopleNearByActivity.this);
				adapter_1 = new Popwindows_Adapter_1(PeopleNearByActivity.this);
				type_list.setAdapter(adapter_1);
				type_list.setOnItemClickListener(new OnItemClickListener() {

					@Override
					public void onItemClick(AdapterView<?> arg0, View arg1,
							int arg2, long arg3) {
						// TODO Auto-generated method stub
						interest_type = Interestlist.get(arg2).getId();
						if (jingdu != null && weidu != null) {
							Page = 0;
							main_byModels.clear();
							xListView1.startLoadMore();
						} else {
							handler.sendEmptyMessage(5);
						}
						popup.dismiss();
					}
				});
				break;
			case 3:
				Utils.ExitPrgress(PeopleNearByActivity.this);
				Utils.showMessage(PeopleNearByActivity.this, getResources()
						.getString(R.string.l_xa10));
				onLoad();
				break;
			case 4:
				Utils.ExitPrgress(PeopleNearByActivity.this);
				main_byModels.addAll(byModels);
				x1Adapter.notifyDataSetChanged();
				onLoad();
				break;
			case 5:
				Utils.showMessage(PeopleNearByActivity.this, getResources()
						.getString(R.string.l_xb108));
				onLoad();
				break;
			default:
				break;
			}
		}
	};

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		goToTheTitle();
		setContentView(R.layout.activity_people_near_by);
		uid = Utils.getUid(PeopleNearByActivity.this);
		init();
		InitMyXListView1();
		// settingPopWindow();
	}

	private void settingPopWindow(View v) {
		// TODO Auto-generated method stub
		LayoutInflater inflater = LayoutInflater
				.from(PeopleNearByActivity.this);
		View root = inflater.inflate(
				R.layout.fragment_club_overview_popwindows, null);
		type_list = (ListView) root.findViewById(R.id.type_list);
		popwindows_display = (ImageView) root
				.findViewById(R.id.popwindows_display);
		popwindows_display_1 = (ImageView) root
				.findViewById(R.id.popwindows_display_1);
		popwindows_display.setVisibility(View.GONE);
		popwindows_display_1.setVisibility(View.VISIBLE);
		popup = new PopupWindow(root, LinearLayout.LayoutParams.MATCH_PARENT,
				360);
		popup.setWidth(LayoutParams.MATCH_PARENT);
		popup.setHeight(LayoutParams.WRAP_CONTENT);
		popup.setBackgroundDrawable(new BitmapDrawable());
		popup.setFocusable(true);
		popup.setTouchable(true);
		popup.setOutsideTouchable(true);
		Interest();
		popup.showAsDropDown(v);
	}

	private void init() {
		// TODO Auto-generated method stub
		Page = 1;
		main_byModels = new ArrayList<nearByModel>();
		Interestlist = new ArrayList<InterestModel>();
		returnButton = (Button) this.findViewById(R.id.people_near_by_return);
		returnButton.setOnClickListener(PeopleNearByActivity.this);
		chose_interest = (Button) this.findViewById(R.id.chose_interest);
		chose_interest.setOnClickListener(PeopleNearByActivity.this);
		x1Adapter = new XListView1Adapter(PeopleNearByActivity.this);
	}

	private void Interest() {
		Utils.showPrgress(PeopleNearByActivity.this);
		MyThreadTool.fixedThreadPool.execute(new Runnable() {
			@Override
			public void run() {
				// TODO Auto-generated method stub
				Interestlist.clear();
				listsModel = new ListsModel();
				Map<String, Object> map = new HashMap<String, Object>();
				map.put("type", "xingqu");
				map.put("languageType",
						Dialog.getSystemLanguageType(PeopleNearByActivity.this));
//				   
				String content = Utils.sendRequest(map, Constants.BadiUrl_1
						+ "type/listType");
				if (content != null) {
					//    ("结果是:" + content);
					Results results = Utils.checkResult_NNN(
							getApplicationContext(), content);
//					   
					if (results != null && results.getRetmsg() != null) {
						//    
//						   ("得到的兴趣结果是:" + content);
						try {
							// Interestlist = JSONUtils.getListByJsonString(
							// results.getRetmsg(), InterestModel.class);
							listsModel = JSONUtils.getEntityByJsonString(
									results.getRetmsg(), ListsModel.class);
							if (listsModel.getLists() != null
									&& !listsModel.getLists().isEmpty()) {
								Interestlist.addAll(listsModel.getLists());
							}
							InterestModel model = new InterestModel();
							model.setId("0");
							model.setName(getResources().getString(
									R.string.Nearby));
							model.setGold("10");
							Interestlist.add(0, model);
							handler.sendEmptyMessage(2);
						} catch (JSONException e) {
//							   ("解析出错");
							   
						} catch (Exception e) {
							// TODO Auto-generated catch block
//							   
							   
						}
					} else {
						handler.sendEmptyMessage(3);
					}
				} else {
					handler.sendEmptyMessage(1);
				}
			}
		});
	}

	private void nearBy(final int page) {
		MyThreadTool.fixedThreadPool.execute(new Runnable() {
			@Override
			public void run() {
				// TODO Auto-generated method stub
				byModels = new ArrayList<nearByModel>();
				Map<String, Object> map = new HashMap<String, Object>();

				map.put("uid", uid);
				map.put("typeid", interest_type);
				map.put("map_x", weidu);
				map.put("map_y", jingdu);
				map.put("page", page);
				map.put("pageNum", "10");
				map.put("distance", "2");
				//    ("搜索附近的人传送数据:" + map.toString());
				String content = Utils.sendRequest(map, Constants.BadiUrl_1
						+ "user/nearBy");
				if (content != null) {
//					   ("搜索附近的人返回的结果是:" + content);
					Results results = Utils.checkResult_NNN(
							getApplicationContext(), content);
					if (results != null && !results.getRetmsg().equals("null")
							&& results.isRet()) {
//						   
						try {
							byModels = JSONUtils.getListByJsonString(
									results.getRetmsg(), nearByModel.class);
							handler.sendEmptyMessage(4);
						} catch (Exception e) {
							// TODO Auto-generated catch block
//							   
							   
						}
					} else {
						handler.sendEmptyMessage(3);
					}
				} else {
					handler.sendEmptyMessage(1);
				}
			}
		});
	}

	@Override
	public void onClick(View v) {
		// TODO Auto-generated method stub
		switch (v.getId()) {
		case R.id.people_near_by_return:
			PeopleNearByActivity.this.finish();
			overridePendingTransition(R.anim.slide_left2, R.anim.slide_right2);
			break;
		case R.id.chose_interest:
			settingPopWindow(chose_interest);
			break;
		}
	}

	public void InitMyXListView1() {
		xListView1 = (XListView) this.findViewById(R.id.people_near_xListView1);
		xListView1.setPullLoadEnable(true);
		xListView1.setAdapter(x1Adapter);
		xListView1.setXListViewListener(this);
		location();
	}

	@Override
	public void onRefresh() {
		// TODO Auto-generated method stub
		if (jingdu != null && weidu != null) {
			Page = 1;
			main_byModels.clear();
			nearBy(Page);
		} else {
			handler.sendEmptyMessage(5);
		}
	}

	protected void onLoad() {
		// TODO Auto-generated method stub
		xListView1.stopRefresh();
		xListView1.stopLoadMore();
		xListView1.setRefreshTime(getResources().getString(R.string.l_xb109));
	}

	@Override
	public void onLoadMore() {
		// TODO Auto-generated method stub
		if (jingdu != null && weidu != null) {
			nearBy(++Page);
		} else {
			handler.sendEmptyMessage(5);
		}
	}

	class XListView1Adapter extends BaseAdapter {
		private DisplayImageOptions options;
		private Context context;

		public XListView1Adapter(Context context) {
			this.context = context;
			options = new DisplayImageOptions.Builder()
					.showStubImage(R.drawable.ic_stub)
					.showImageForEmptyUri(R.drawable.noimage)
					.showImageOnFail(R.drawable.noimage).cacheInMemory()
					.cacheOnDisc().displayer(new RoundedBitmapDisplayer(5))
					.build();
		}

		@Override
		public int getCount() {
			// TODO Auto-generated method stub
			return main_byModels.size();
		}

		@Override
		public Object getItem(int position) {
			// TODO Auto-generated method stub
			return main_byModels.get(position);
		}

		@Override
		public long getItemId(int position) {
			// TODO Auto-generated method stub
			return position;
		}

		@Override
		public View getView(final int position, View convertView,
				ViewGroup parent) {
			// TODO Auto-generated method stub user_list_item_img
			// user_list_item_from_1
			LayoutInflater inflater = LayoutInflater
					.from(PeopleNearByActivity.this);
			convertView = inflater.inflate(
					R.layout.fragment_indexclub2_import_layout, null);
			ImageView user_list_item_img = (ImageView) convertView
					.findViewById(R.id.user_list_item_img);
			TextView user_list_item_name = (TextView) convertView
					.findViewById(R.id.user_list_item_name);
			TextView user_list_item_from = (TextView) convertView
					.findViewById(R.id.user_list_item_from);
			TextView user_list_item_from_1 = (TextView) convertView
					.findViewById(R.id.user_list_item_from_1);
			TextView user_list_item_from_2 = (TextView) convertView
					.findViewById(R.id.user_list_item_from_2);
			Button user_list_item_add = (Button) convertView
					.findViewById(R.id.user_list_item_add);
			ImageLoader.getInstance().displayImage(
					Constants.BadiDownImgUrl
							+ main_byModels.get(position).getHead()
							+ Constants.appPhoto4img, user_list_item_img,
					options);
			// 头像
			user_list_item_img.setOnClickListener(new View.OnClickListener() {

				@Override
				public void onClick(View v) {
					// TODO Auto-generated method stub
					if (main_byModels
							.get(position)
							.getId()
							.equals(""
									+ Utils.getUid(PeopleNearByActivity.this))) {
						// Intent intent=new
						// Intent(PeopleNearByActivity.this,AfterLandingActivity.class);
						// startActivity(intent);
					} else {
						Intent intent = new Intent(PeopleNearByActivity.this,
								SeeOtherPeopleSpaceActivity.class);
						intent.putExtra("friend_id", main_byModels
								.get(position).getId());
						startActivity(intent);
					}

				}
			});
			user_list_item_name.setText(main_byModels.get(position)
					.getNickName());
			user_list_item_from_1.setVisibility(View.GONE);
			user_list_item_from_2.setVisibility(View.GONE);
			user_list_item_from.setText(getResources().getString(
					R.string.wx2_29)
					+ back_distance(main_byModels.get(position).getDistance()));
			if (main_byModels.get(position).getIs_firend().equals("0")) {
				user_list_item_add.setText(""
						+ getResources().getString(R.string.l_xb129));
				user_list_item_add.setTextColor(context.getResources()
						.getColor(R.color.green));
				user_list_item_add.setOnClickListener(new OnClickListener() {

					@Override
					public void onClick(View arg0) {
						Intent intent = new Intent(PeopleNearByActivity.this,
								AddFriendValidationActivity.class);
						intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
						intent.putExtra("id", main_byModels.get(position)
								.getId());
						context.startActivity(intent);
					}
				});
			} else {
				user_list_item_add.setText(""
						+ getResources().getString(R.string.l_xb128));
				user_list_item_add.setTextColor(context.getResources()
						.getColor(R.color.gray));
			}

			return convertView;
		}

		private String back_distance(String d) {
			double ind = Double.valueOf(d);
			if (ind >= 1000) {
				return Utils.BackXXXDian(((double) (ind / 1000)), 2)
						+ getResources().getString(R.string.l_xb110);
			} else {
				int sd = (int) ind;
				return Utils.BackXXXDian(ind, 2)
						+ getResources().getString(R.string.l_xb111);
			}

		}
	}

	private class Popwindows_Adapter_1 extends BaseAdapter {
		private Context context;

		public Popwindows_Adapter_1(Context context) {
			this.context = context;
		}

		@Override
		public int getCount() {
			// TODO Auto-generated method stub
			return Interestlist.size();
		}

		@Override
		public Object getItem(int arg0) {
			// TODO Auto-generated method stub
			return Interestlist.get(arg0);
		}

		@Override
		public long getItemId(int arg0) {
			// TODO Auto-generated method stub
			return arg0;
		}

		@Override
		public View getView(int arg0, View arg1, ViewGroup arg2) {
			LayoutInflater inflater = LayoutInflater.from(context);
			arg1 = inflater.inflate(
					R.layout.fragment_club_overview_popwindows_item, null);
			TextView popwindows_itmes_name = (TextView) arg1
					.findViewById(R.id.popwindows_itmes_name);
			popwindows_itmes_name.setText(Interestlist.get(arg0).getName());
			return arg1;
		}

	}

	private void location() {
		// 这只是一个使用接口的模板
		final AMapLocationUtils aMapLocationUtils = new AMapLocationUtils(
				PeopleNearByActivity.this);
		new Thread(new Runnable() {
			boolean isRun = true;

			@Override
			public void run() {
				// TODO Auto-generated method stub

				while (isRun) {
					try {
						Thread.sleep(200);
					} catch (InterruptedException e) {
						// TODO Auto-generated catch block
						   
					}
					aMapLocationUtils
							.setOnAMapLocationClistener(new getAMapLocation() {

								@Override
								public void getAMapLocation(
										AMapLocation aMapLocation) {
									// TODO Auto-generated method stub
//									   
									if (aMapLocation != null) {
//										   
//												"经度-》"
//														+ aMapLocation
//																.getLongitude()
//														+ "纬度=》"
//														+ aMapLocation
//																.getLatitude());
										jingdu = ""
												+ aMapLocation.getLongitude();
										weidu = "" + aMapLocation.getLatitude();
										nearBy(Page);
										isRun = false;
									}

								}
							});
				}

			}
		}).start();
	}
}
